package com.flying.client.network;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.flying.client.network.msg.ORMsg;
import com.flying.client.utils.Logger;

public class MsgDispatchHandler extends SimpleChannelUpstreamHandler{
	private static final Logger logger = Logger.getLogger(MsgDispatchHandler.class.getName());
	
	private NetworkProvider networkProvider = null;
	
	public MsgDispatchHandler(NetworkProvider networkProvider)
	{
		this.networkProvider = networkProvider;
	}
	@Override
	public void messageReceived(
            ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		
		logger.debug("messageReceived msgEvent="+e.getMessage());
		
		if (e.getMessage() instanceof ORMsg)
		{
			ORMsg msg = (ORMsg) e.getMessage();
			
			networkProvider.onReceivedMsg(msg);
		}
		
        super.messageReceived(ctx, e);
    }
	
	@Override
	public void exceptionCaught(
            ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        try
        {
        	ctx.sendUpstream(e);
        }
        catch(Exception ex)
        {
        	logger.debug("exceptionCaught Error="+ex);
        }
    }
}
